import json
import os
import sys
from app import app
from models import db, AccessLog

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

def migrate_json_to_mysql():
    """将JSON文件中的访问日志迁移到MySQL数据库"""
    
    # JSON文件路径
    json_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'access_log.json')
    
    # 检查JSON文件是否存在
    if not os.path.exists(json_file_path):
        print(f"JSON文件不存在: {json_file_path}")
        return False
    
    try:
        # 读取JSON文件
        with open(json_file_path, 'r', encoding='utf-8') as f:
            logs = json.load(f)
        
        print(f"从JSON文件读取到 {len(logs)} 条记录")
        
        # 迁移记录到数据库
        migrated_count = 0
        for log_entry in logs:
            # 创建AccessLog对象
            access_log = AccessLog(
                filename=log_entry.get('filename', ''),
                ip=log_entry.get('ip', ''),
                user_agent=log_entry.get('user_agent', '')
            )
            
            # 解析时间戳
            timestamp_str = log_entry.get('timestamp', '')
            if timestamp_str:
                try:
                    # 将字符串时间转换为datetime对象
                    from datetime import datetime
                    access_log.timestamp = datetime.strptime(timestamp_str, '%Y-%m-%d %H:%M:%S')
                except ValueError:
                    print(f"无法解析时间戳: {timestamp_str}")
                    continue
            
            # 添加到数据库会话
            db.session.add(access_log)
            migrated_count += 1
        
        # 提交所有更改
        db.session.commit()
        print(f"成功迁移 {migrated_count} 条记录到MySQL数据库")
        
        return True
        
    except Exception as e:
        print(f"迁移过程中发生错误: {e}")
        db.session.rollback()
        return False

if __name__ == '__main__':
    with app.app_context():
        # 初始化数据库
        db.create_all()
        
        # 执行迁移
        success = migrate_json_to_mysql()
        
        if success:
            print("数据迁移完成!")
        else:
            print("数据迁移失败!")